<script setup>
	import { computed, onMounted, ref, watch } from 'vue'
	import { message } from 'ant-design-vue'
	import { EyeOutlined, LinkOutlined } from '@ant-design/icons-vue'
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'
	import apiDiscoveryApi from '@/views/plugin/dashboard/api/apiDiscoveryApi'
	import datasetApi from '@/views/plugin/dashboard/api/datasetApi'

	const props = defineProps({
		modelValue: {
			type: Object,
			default: () => ({
				apiPath: '',
				method: 'GET',
				headers: '{}',
				params: '{}'
			})
		}
	})

	const emit = defineEmits(['update:modelValue', 'change'])

	// 表单引用
	const formRef = ref()

	// 状态管理
	const loading = ref(false)
	const apiListLoading = ref(false)
	const previewLoading = ref(false)

	// API接口列表
	const apiList = ref([])
	const filteredApiList = ref([])
	const apiSearchValue = ref('')

	// 支持的公式列表
	const supportedFormulas = ref([])

	// 数据预览
	const previewDataList = ref([])
	const showPreview = ref(false)

	// 计算属性：格式化的API选项
	const apiOptions = computed(() => {
		return filteredApiList.value.map((api) => ({
			label: `${api.method} ${api.path} - ${api.summary}`,
			value: api.path,
			method: api.method,
			summary: api.summary,
			description: api.description
		}))
	})

	// 监听API搜索
	watch(apiSearchValue, (newValue) => {
		if (!newValue) {
			filteredApiList.value = apiList.value
		} else {
			filteredApiList.value = apiList.value.filter(
				(api) =>
					api.path.toLowerCase().includes(newValue.toLowerCase()) ||
					api.summary.toLowerCase().includes(newValue.toLowerCase())
			)
		}
	})

	// 监听选中的API路径变化
	watch(
		() => props.modelValue.apiPath,
		(newPath) => {
			if (newPath) {
				// 确保方法始终为GET
				if (props.modelValue.method !== 'GET') {
					const updatedValue = {
						...props.modelValue,
						method: 'GET'
					}
					emit('update:modelValue', updatedValue)
					emit('change', updatedValue)
				}
			}
		}
	)

	// 监听配置变化
	watch(
		() => props.modelValue,
		(newValue) => {
			emit('change', newValue)
		},
		{ deep: true }
	)

	// 加载API接口列表
	const loadApiList = async () => {
		try {
			apiListLoading.value = true
			const response = await apiDiscoveryApi.getApiList()
			apiList.value = response || []
			filteredApiList.value = apiList.value
		} catch (error) {
			console.error('加载API接口列表失败:', error)
			message.error('加载API接口列表失败')
		} finally {
			apiListLoading.value = false
		}
	}

	// 加载支持的公式列表
	const loadSupportedFormulas = async () => {
		try {
			const response = await datasetApi.getSupportedFormulas()
			supportedFormulas.value = Object.entries(response || {}).map(([key, description]) => ({
				key,
				description,
				placeholder: `\${${key}}`
			}))
		} catch (error) {
			console.error('加载公式列表失败:', error)
		}
	}

	// 测试HTTP连接
	const testConnection = async () => {
		if (!props.modelValue.apiPath) {
			message.warning('请选择API接口')
			return
		}

		try {
			loading.value = true
			await dataConnectorApi.testConnection({
				type: 'HTTP',
				config: {
					...props.modelValue,
					// 确保方法为GET
					method: 'GET',
					// 本地API不需要baseUrl，设置为空字符串
					baseUrl: ''
				}
			})
			message.success('连接测试成功')
		} catch (error) {
			console.error('连接测试失败:', error)
			const errorMessage = error.response?.data?.message || error.message || '未知错误'
			message.error('连接测试失败：' + errorMessage)
		} finally {
			loading.value = false
		}
	}

	// 数据预览
	const handlePreviewData = async () => {
		if (!props.modelValue.apiPath) {
			message.warning('请选择API接口')
			return
		}

		try {
			previewLoading.value = true

			// 构建预览配置，支持临时配置预览
			const previewConfig = {
				type: 'HTTP',
				config: {
					...props.modelValue,
					// 确保方法为GET
					method: 'GET',
					// 本地API不需要baseUrl，设置为空字符串
					baseUrl: ''
				},
				params: {} // 可以传入额外的预览参数
			}

			const response = await dataConnectorApi.previewData(previewConfig)
			previewDataList.value = response || []
			showPreview.value = true

			if (previewDataList.value.length === 0) {
				message.info('API接口返回空数据')
			}
		} catch (error) {
			console.error('数据预览失败:', error)
			const errorMessage = error.response?.data?.message || error.message || '未知错误'
			message.error('数据预览失败：' + errorMessage)
		} finally {
			previewLoading.value = false
		}
	}

	// 插入公式到参数
	const insertFormula = (formula, targetField) => {
		const currentValue = props.modelValue[targetField] || ''
		const newValue = currentValue + formula.placeholder
		const updatedValue = {
			...props.modelValue,
			[targetField]: newValue
		}
		emit('update:modelValue', updatedValue)
		emit('change', updatedValue)
	}

	// 验证JSON格式
	const validateJson = (value) => {
		if (!value || value.trim() === '') return true
		try {
			JSON.parse(value)
			return true
		} catch {
			return false
		}
	}

	// 表单验证方法
	const validate = () => {
		return formRef.value.validate()
	}

	// 重置表单方法
	const resetFields = () => {
		formRef.value.resetFields()
	}

	// 暴露方法给父组件
	defineExpose({
		validate,
		resetFields,
		testConnection,
		previewData: handlePreviewData
	})

	// 组件挂载时加载数据
	onMounted(() => {
		loadApiList()
		loadSupportedFormulas()
	})
</script>

<template>
	<div>
		<a-form ref="formRef" :model="modelValue" layout="vertical">
			<a-row :gutter="16">
				<!-- API接口选择器 -->
				<a-col :span="24">
					<a-form-item :rules="[{ required: true, message: '请选择API接口' }]" label="API接口" name="apiPath">
						<a-select
							:filter-option="false"
							:loading="apiListLoading"
							:value="modelValue.apiPath"
							placeholder="请选择或搜索API接口"
							show-search
							@change="
								(value) => {
									const updatedValue = { ...modelValue, apiPath: value }
									emit('change', updatedValue)
								}
							"
							@search="(value) => (apiSearchValue = value)"
						>
							<a-select-option
								v-for="option in apiOptions"
								:key="option.value"
								:title="option.description"
								:value="option.value"
							>
								<div class="flex items-center justify-between">
									<span class="text-sm">{{ option.label }}</span>
									<a-tag
										:color="option.method === 'GET' ? 'green' : option.method === 'POST' ? 'blue' : 'orange'"
										size="small"
									>
										{{ option.method }}
									</a-tag>
								</div>
							</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>

				<!-- 操作按钮 -->
				<a-col :span="24">
					<a-form-item class="mb-0" label="操作">
						<div class="flex flex-wrap gap-3">
							<a-button :loading="loading" type="primary" @click="testConnection">
								<template #icon>
									<LinkOutlined />
								</template>
								测试连接
							</a-button>
							<a-button :loading="previewLoading" @click="handlePreviewData">
								<template #icon>
									<EyeOutlined />
								</template>
								数据预览
							</a-button>
						</div>
						<div class="text-xs text-gray-500 mt-2">仅支持GET请求方法的API接口</div>
					</a-form-item>
				</a-col>

				<!-- 请求头配置 -->
				<a-col :span="24">
					<a-form-item
						:rules="[
							{
								validator: (_, value) => {
									if (!validateJson(value)) {
										return Promise.reject('请输入有效的JSON格式')
									}
									return Promise.resolve()
								}
							}
						]"
						label="请求头"
						name="headers"
					>
						<div class="space-y-2">
							<a-textarea
								:rows="4"
								:value="modelValue.headers"
								placeholder='{"Content-Type": "application/json", "Authorization": "Bearer ${current_user_token}"}'
								@change="
									(e) => {
										const updatedValue = { ...modelValue, headers: e.target.value }
										emit('change', updatedValue)
									}
								"
							/>
							<div class="text-xs text-gray-500">支持JSON格式的请求头配置，可使用公式占位符如 ${current_user_id}</div>
						</div>
					</a-form-item>
				</a-col>

				<!-- 请求参数配置 -->
				<a-col :span="24">
					<a-form-item
						:rules="[
							{
								validator: (_, value) => {
									if (!validateJson(value)) {
										return Promise.reject('请输入有效的JSON格式')
									}
									return Promise.resolve()
								}
							}
						]"
						label="请求参数"
						name="params"
					>
						<div class="space-y-2">
							<a-textarea
								:rows="4"
								:value="modelValue.params"
								placeholder='{"userId": "${current_user_id}", "deptId": "${current_user_dept_id}", "startDate": "${current_date}"}'
								@change="
									(e) => {
										const updatedValue = { ...modelValue, params: e.target.value }
										emit('change', updatedValue)
									}
								"
							/>
							<div class="text-xs text-gray-500">支持JSON格式的请求参数，可使用公式占位符进行动态替换</div>
						</div>
					</a-form-item>
				</a-col>

				<!-- 公式助手 -->
				<a-col :span="24">
					<a-collapse>
						<a-collapse-panel key="formulas" header="公式助手">
							<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-2">
								<a-tooltip v-for="formula in supportedFormulas" :key="formula.key" :title="formula.description">
									<a-button class="text-left" size="small" type="dashed" @click="insertFormula(formula, 'params')">
										{{ formula.placeholder }}
									</a-button>
								</a-tooltip>
							</div>
							<div class="mt-2 text-xs text-gray-500">
								点击公式按钮可将公式插入到请求参数中，支持在请求头和请求参数中使用
							</div>
						</a-collapse-panel>
					</a-collapse>
				</a-col>
			</a-row>
		</a-form>

		<!-- 数据预览模态框 -->
		<a-modal
			:destroy-on-close="true"
			:footer="null"
			:open="showPreview"
			title="数据预览"
			width="80%"
			@cancel="showPreview = false"
		>
			<div v-if="previewDataList.length > 0">
				<a-table
					:columns="Object.keys(previewDataList[0] || {}).map((key) => ({ title: key, dataIndex: key, key }))"
					:data-source="previewDataList"
					:pagination="{ pageSize: 10 }"
					:scroll="{ x: 'max-content' }"
					size="small"
				/>
			</div>
			<a-empty v-else description="暂无数据" />
		</a-modal>
	</div>
</template>
